(function($) {
	
	//Login wird erst nach erfolgreicher Socketverbindung abgewickelt
	
	
	// =================================================== INIT START
	// ======================================================
	var user;
	var userID;
	var isSuperUser = false;
	var sidebar_height = $("#sidebar").height();
	var socket;
	var trigger = false;
	var richtigeID;
	var rang;
	var gameState;
	var clear;

	var source = new EventSource("UserListServlet"); // SSE for playerlist

	$(document).ready(function() {
		
		catalogRequest();

		

	});
	
	$("#main_content").css("height", sidebar_height - 60); // sets the main_content div to the same height as the right navbar
	$('#login_box_content').css("margin-top", (sidebar_height / 2) - 30); // sets the login_box div in the middle of the main_content div box


	// ============= LISTENERS START

	// ------------------------------- Error_box_listener (red box can be closed smoothly) -----------------
	$('#login_error_box').bind('close', function() {
		$('#login_error_box').fadeOut("slow");
	});
	$('#start_box_info').bind('close', function() {
		$('#start_box_info').fadeOut("slow");
	});

	// ------------------------------- Button listener ------------------------------------------------------
	$("#new_button").on('click', function(e) {
		gameState = 0;
        $("#start_button").addClass("disabled");
                $("#gameover_content").fadeOut("slow");
                setTimeout(function(){
                        $("#login_box_content").fadeIn("slow");
                        }, 600);
         $("#new_button").prop('disabled', true);
	});
	$('#login_button').on('click', function(e) {
		if ($('#login_field').val().match(/[^a-zA-Z0-9]/g)) {
			$('#login_error_box_description').text("Only A-Z a-z 0-9 allowed");
			$('#login_error_box').effect("pulsate", {
				times : 1
			}, 1500);
		} else {
			if ($('#login_field').val() != "") {
				$('#login_error_box').css("display", "hide");
				socket = new WebSocket("ws://localhost:80/WebQuiz/WebSocketQuizServlet");  
				//socket = new WebSocket("ws://pluto.hs-weingarten.de/~webprog02/tomcat/WebSocketQuizServlet");  
				socket.onclose = socketClose;
				socket.onopen = socketOpen;
				socket.onerror = socketError;
				socket.onmessage = socketMessage;
			} else {
				$('#login_error_box_description').text("Please enter a name");
				$('#login_error_box').effect("pulsate", {
					times : 1
				}, 1500);
			}
		}
	});
	
	$('#start_button').on('click', function(e) {
		//$('#start_button')
		$("#start_button").prop('disabled', true);
		sendStart();
	});

	// ----------------------------------- SSE Listener --------------------------------------

	source.addEventListener('UserListRefresh', function(e) {
		var playerList = e.data.split("\n"); // Jede Zeile im SSE setzt sich
		// zusammen aus NAME;PUNKTE;ID
		// durch split wird dieses
		// String an den ; getrennt und
		// in einem Array abgelegt. @see
		// UserListServlet
		console.log("===================== SSE start ===================");
		console.log("[INFO] received SSE: String: " + playerList
				+ " player count: " + playerList.length);
		$('#player_list li').remove();
		for ( var i = 0; i < playerList.length; i++) {
			var player = playerList[i].split(";");
			if(player[2] == userID)
				rang = i+1;
			if(player[2]=="0"){
				$("#player_list").append(
						'<li class="row player"><div class="span2"><strong>' + player[0]
								+ '</strong></div><div class="span1"><strong>' + player[1]
								+ '</strong></div></li>');
			}else{
				$("#player_list").append(
						'<li class="row player"><div class="span2">' + player[0]
								+ '</div><div class="span1">' + player[1]
								+ '</div></li>');
			}
			
			sidebar_height = $("#sidebar").height();
			console.log("Player: " + player[0] + " Score: " + player[1]
					+ " ID: " + player[2]);
			$("#main_content").css("height", sidebar_height - 60);
			$('#login_box_content')
					.css("margin-top", (sidebar_height / 2) - 30); // setzt die Loginbox vertical in die Mitte
			//$('#start_box_content').css("margin-top", (sidebar_height / 2) - 30);
			
		}
		console.log("===================== SSE end =====================");
	}, false);

	 

	
	
	// ================= functions =====================
	
	

   // Funktion die beim schließen und aktualisieren den player ausloggt.
	function logout(){
		socket.close();
		$.ajax({
			type : "POST",
			url : 'LogoutServlet',
			data : {
				'user' : user
			},
			async : false,
		});
	}
	
	
	//------------------ Login Funktion -----------------------
	
	function login() {
		var responseXML;
		$.ajax({
			type : "POST",
			url : "LoginServlet",
			data : {
				user : $('#login_field').val()
			},
			dataType : "xml",
			success : function(xml) {
				if ($(xml).find('loginResponse').attr("id") == 0) {
					$(xml).find('loginResponse').each(function() {
						responseXML = xml;
						var playerID = $(this).find("playerID").text();
					    console.log("Player eingeloggt:"+ playerID);
					    userID= playerID;
						if (playerID == "0") {
							$('#start_button').html("Start<i class='icon-chevron-right icon-white'>");
							isSuperUser = true;
						}else{
							$('#start_button').html("Wait ...");
							isSuperUser =false;
						}
					});
					
					$('#start_box_content').css("margin-top", - $("#login_box_content").height());
					$('#login_box_content').fadeOut("slow");
					$("#start_box_content").fadeIn("slow",function(){$('#start_box_content').css("margin-top", (sidebar_height / 2) - 30);});
					user = $('#login_field').val();
					catalogRequest();
					$('#login_error_box').fadeOut("slow");
					return true;
				}
				if ($(xml).find('loginResponse').attr("id") == 1) {
					trigger=true;
					socket.close();
					responseXML = xml;
					$(xml).find('loginResponse').each(
							function() {
								var ErrorDescription = $(this).find(
										"ErrorDescription").text();
								$('#login_error_box_description').text(
										ErrorDescription);
							});
					$('#login_error_box').effect("pulsate", {
						times : 1
					}, 1500);

					return false;
				}
			}
		});
	}

	// Beim Aktualisieren und neu laden -> Spieler ausloggen
	window.onbeforeunload = logout;

	function catalogRequest() {
		$.ajax({
			type : "POST",
			url : "CatalogServlet",
			Data : {
				'catalogRequest' : "catalogRequest"
			},
			dataType : "xml",
			success : function(xml) {
				$('#catalogListe li').remove();
				console.log($(xml));	
				$(xml).find('catalogResponse').find('catalogEntry').each(
						function(index) {

							var catalogEntryName = $(this).text();
							var li_element = document.createElement('li');
							var a_element = document.createElement('a');
							

							a_element.innerHTML = catalogEntryName;
							
							if(isSuperUser)
								a_element.onclick = changeCatalog;
							
							
							li_element.appendChild(a_element);
							if(socket){
								if ($(this).attr("selected") == 1) {
									li_element.setAttribute("class", "active");
								}
							}

							document.getElementById('catalogListe')
									.appendChild(li_element);

						});
				$('#scrollable').jScrollPane({
					hideFocus : true
				});
				

				if (!isSuperUser) {
					disableCatalogHover();

				}
				


			}
		});
	}
	function sendStart(){
		var XML = document.createElement("message");
		var Node = document.createElement("startgame");
		var playername = document.createElement("playername");
		var playerid = document.createElement("playerid");
		playername.appendChild(document.createTextNode(user));
		playerid.appendChild(document.createTextNode(userID));
		Node.appendChild(playername);
		Node.appendChild(playerid);
		XML.appendChild(Node);
		console.log(XML.innerHTML);
		if(socket){										//erst wennd er Socket initialisiert wurde funktioniert das senden
			socket.send(XML.innerHTML);
		}		
	}
	function changeCatalog(source) {
		
		var XML = document.createElement("message");
		var Node = document.createElement("changeCatalog");
		var playername = document.createElement("playername");
		var playerid = document.createElement("playerid");
		var catalog = document.createElement("catalog");
		
		playername.appendChild(document.createTextNode(user));
		playerid.appendChild(document.createTextNode(userID));
		catalog.appendChild(document.createTextNode(source.target.innerHTML));
		
		Node.appendChild(playername);
		Node.appendChild(playerid);
		Node.appendChild(catalog);
		
		
		XML.appendChild(Node);
		if(socket){										//erst wennd er Socket initialisiert wurde funktioniert das senden
			socket.send(XML.innerHTML);
		}
	}
	function socketError(error){
		alert("Error "+error);
	}
	function socketOpen(){
		login(); 
	}
	function socketClose(){
		if(gameState==4){
			catalogRequest();
		}else{
			
			if(trigger==false){
				$("#start_box_content").fadeOut("slow");
				$("#gameContent").fadeOut("slow");
				setTimeout(function(){
					$('#login_box_content').fadeIn("slow");
					$('#login_error_box_description').text(
							"User error.");
					$('#login_error_box').effect("pulsate", {
						times : 1
					}, 1500);
					}, 600);

				catalogRequest();

			}else{trigger=false;}
		}
	}
	function socketMessage(message){
		console.log("::WEBSOCKET_MESSAGE::"+message.data);
		var doc = StringtoDOM(message.data);
		//Nachfolgend die Messageloop des Clients
		$(doc).find('refreshcatalog').each(
				function() {
					catalogRequest();
				});
		$(doc).find('gameready').each(
				function() {
					if(isSuperUser==true&&gameState !=2){
						$("#start_button").removeClass("disabled");
						$("#start_button").removeAttr("disabled");
					}
				});
		$(doc).find('gamenotready').each(
				function() {
					$("#start_button").addClass("disabled");
				});
		$(doc).find('responsequestion').each(
				function() {
					$('#anwers li').remove();
					var question = $(this).find("question").text();	
					document.getElementById('question').innerHTML = "<strong>"+question+"</strong>";
					
					richtigeID = $(this).find('correct').text();
					var timeOut = $(this).find('timeout').text() / 1000;
					
					$(this).find('answers').each(function() {
						$(this).find('answer').each(function(index){
						var answer = $(this).text();
						
						
						var li_element = document.createElement('li');
						var a_element = document.createElement('a');
						
						a_element.innerHTML = answer;
						
						
						
						a_element.setAttribute("id", "answer"+index);
						a_element.setAttribute("name", index);
						li_element.setAttribute("id", "lianswer"+index);
						a_element.onclick = sendAnswerID;
						a_element.setAttribute("class", "spacerAnswer");
						li_element.appendChild(a_element);
						
						
						document.getElementById('anwers')
								.appendChild(li_element);
						
						});
					});
					$("#gameContent").fadeIn("slow");
					
					$("#timer1").empty();
					$("#timer1").timer360({
						  radius      : 50.5,
						  fillColor   : "#c4e1ff",
						  strokeColor : "#007fff",
						  strokeWidth : 10,
						  intervals   : [],
						  interval   : [timeOut],
						  seconds     : true,
						});	
					
				});
		$(doc).find('questiontimeout').each(
				function() {
					console.log("Timeout bekommen");

				});
		$(doc).find('gamestarted').each(

				function() {
					gameState =2;
					$("#start_box_content").fadeOut("slow");
					setTimeout(function(){
						requestQuestion();
						}, 600);
					
					//$('#start_button').fadeOut("slow");
					
					
					//hover effekte entfernen, kataloge koennnen ab jetzt nicht mehr geaendert werden
					$(".nav-list li a").hover(function() {
						if($(this).parent().hasClass("active")){	
						}else{
							$(this).css('background-color', 'transparent');
							$(this).css('color', '#000000');
						}
					}, function() {
						if($(this).parent().hasClass("active")){	
							
						}else{
							$(this).css('background-color', 'transparent');
							$(this).css('color', '#000000');
						}
					});
				});
		$(doc).find('anwerright').each(
				function() {
					markRightAnswer();
					setTimeout(function(){
						$("#gameContent").fadeOut("slow");
						setTimeout(function(){
							requestQuestion();
							}, 600);
						}, 2000);
				});
		$(doc).find('anwerfalse').each(
				function(){
					var selectedID =  $(this).find("geschickteID").text();	
					markWrongAnwer(selectedID);
					setTimeout(function(){
						$("#gameContent").fadeOut("slow");
						setTimeout(function(){
							requestQuestion();
							}, 600);
						}, 2000);
				});
		$(doc).find('gameover').each(
				function() {
					$("#gameover_content").fadeIn("slow");
					$("#new_button").removeClass("disabled");
					$("#new_button").removeAttr("disabled");
					$("#timer1").empty();
					console.log("Game Over!");
					$('#anwers li').remove();
					document.getElementById('messageStatus').innerHTML = "<strong>Spiel beendet.</br> Sie wurden "+rang+".</strong>";
					source.close;
					gameState = 4;
					isSuperUser = false; //sonst werden die cataloge wieder auswaehlbar, nur weil er mal admin war.
					disableCatalogHover();//hover effekte deaktivieren, bei dem catalog request wird wieder die lsite mit katalogen geladen, keines davon wird selektiert sein, weil das spiel vorbei ist.
					
				});
		$(doc).find('gameoverwait').each(
				function() {
					$("#gameover_content").fadeIn("slow");
					$("#timer1").empty();
					console.log("Game Over, please wait for other players");
					$('#anwers li').remove();
					disableCatalogHover();
					document.getElementById('messageStatus').innerHTML = "<strong>Spiel beendet.</br> Warte auf andere Spieler ...</strong";
				});
		
	}
	function markWrongAnwer(selectedID){
		markRightAnswer();
		document.getElementById("answer"+selectedID).setAttribute("class", "activeWrong spacerAnswer");
		
		$("#gameContent .nav-list li a").css('textShadow', "none");
		$("#gameContent .nav-list li a").hover(function() {
				if($(this).hasClass("activeWrong")){
					$(this).css('background-color', '#ff0000');
					$(this).css('color', '#000000');
					//$(this).css('textShadow', "none");
				}else{
					if($(this).hasClass("activeRight")){
						$(this).css('background-color', '#7fff00');
						$(this).css('color', '#000000');
					}else{
						$(this).css('background-color', '#eeeeee');
						$(this).css('color', '#000000');
					}
				}

		}, function() {
			if($(this).hasClass("activeWrong")){	
				$(this).css('background-color', '#ff0000');
				$(this).css('color', '#000000');
			}else{
				if($(this).hasClass("activeRight")){	
					$(this).css('background-color', '#7fff00');
					$(this).css('color', '#000000');
				}else{
					$(this).css('background-color', 'transparent');
					$(this).css('color', '#000000');
				}
			}
		});
	}
	
	function markRightAnswer(){
		document.getElementById("answer0").onclick = null;
		document.getElementById("answer1").onclick = null;
		document.getElementById("answer2").onclick = null;
		document.getElementById("answer3").onclick = null;
		document.getElementById("answer"+richtigeID).setAttribute("class", "activeRight spacerAnswer");
		
		
		$("#gameContent .nav-list li a").hover(function() {
				if($(this).hasClass("activeRight")){
					$(this).css('background-color', '#7fff00');
					$(this).css('color', '#000000');
				}else{
					$(this).css('background-color', '#eeeeee');
					$(this).css('color', '#000000');
				}

		}, function() {
			if($(this).hasClass("activeRight")){	
				$(this).css('background-color', '#7fff00');
				$(this).css('color', '#000000');
			}else{
				$(this).css('background-color', 'transparent');
				$(this).css('color', '#000000');
			}
		});
	}
	
	function sendAnswerID(source){
		
		var XML = document.createElement("message");
		var Node = document.createElement("questionresult");
		var playername = document.createElement("playername");
		var playerid = document.createElement("playerid");
		var answerid = document.createElement("answerid");
		
		playername.appendChild(document.createTextNode(user));
		playerid.appendChild(document.createTextNode(userID));
		
		Node.appendChild(playername);
		Node.appendChild(playerid);
		
		
		//alert("auswahl = "+source.target.getAttribute('name'))
		//alert("richtig = "+richtigeID);
		
		
	
		answerid.appendChild(document.createTextNode(source.target.getAttribute('name')));
		
		Node.appendChild(answerid);
	
		XML.appendChild(Node);
		if(socket){										//erst wennd er Socket initialisiert wurde funktioniert das senden
			socket.send(XML.innerHTML);
		}
	}
	
	
	
	function disableCatalogHover(){
		$(".nav-list li a").hover(function() {
			if($(this).parent().hasClass("active")){	
			}else{
				$(this).css('background-color', 'transparent');
				$(this).css('color', '#000000');
			}
		}, function() {
			if($(this).parent().hasClass("active")){	
				
			}else{
				$(this).css('background-color', 'transparent');
				$(this).css('color', '#000000');
			}
		});
	}
	
	
	//convertiert die Zeichenkette die vom Websocket kommt in ein XML-Objekt
	function requestQuestion(){
		var XML = document.createElement("message");
		var Node = document.createElement("requestQuestion");
		var playername = document.createElement("playername");
		var playerid = document.createElement("playerid");;
		
		playername.appendChild(document.createTextNode(user));
		playerid.appendChild(document.createTextNode(userID));
		
		Node.appendChild(playername);
		Node.appendChild(playerid);;
				
		XML.appendChild(Node);
		if(socket){										//erst wennd er Socket initialisiert wurde funktioniert das senden
			socket.send(XML.innerHTML);
		}
	}
	
	//convertiert die Zeichenkette die vom Websocket kommt in ein XML-Objekt
	function StringtoDOM(text){
        if (window.ActiveXObject){
          var doc=new ActiveXObject('Microsoft.XMLDOM');
          doc.async='false';
          doc.loadXML(text);
        } else {
          var parser=new DOMParser();
          var doc=parser.parseFromString(text,'text/xml');
        }
        return doc;
    }
	function removeTag(tag){
		tag.parentNode.removeChild(tag);
	}


})(jQuery);
